package benny.ApkposStore.Service;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import benny.ApkposStore.db.OrderTableDishs;
import benny.ApkposStore.db.OrderTableNew;
import benny.ApkposStore.db.OrderTablePay;
import benny.ApkposStore.db.OrderTableSubDishs;
import benny.ApkposStore.proto.UnpayOrder;
import benny.ApkposStore.proto.UnpayOrder.POrderTableDishs;
import benny.ApkposStore.proto.UnpayOrder.POrderTableNew;
import benny.ApkposStore.proto.UnpayOrder.POrderTablePay;
import benny.ApkposStore.proto.UnpayOrder.POrderTableSubDishs;
import benny.ApkposStore.proto.UnpayOrder.UploadOrderRequest;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.BinUploader;




public class OrderSyncService extends IntentService {
	
	final private int mSleepTime = 30000; //10s
	final private String tag = "OrderSyncService";
	private String utf8str="";
	
	public OrderSyncService() {
		super("OrderSyncService");
	}
	  
	@Override
	protected void onHandleIntent(Intent intent) {

		while(true) {
			synchronized(this) {
				try {				
					Thread.sleep(mSleepTime);

					syncOrders();
			 					
				} catch (InterruptedException e) {
					Log.e(tag, e.getMessage());					
				} catch (NullPointerException e) {
					Log.e(tag, e.getMessage());
				}
				catch(Exception e){
					Log.e(tag, e.getMessage());
				}
			}
		}
	}
	  
	private void syncOrders() {
		if(Apkglobal.gettoken() == null || Apkglobal.getuser_name() == null) {
			return ; 
		}
		UploadOrderRequest.Builder builder = UnpayOrder.UploadOrderRequest.newBuilder();
		
		while(fetchOnePaiedOrder(builder)) {

			builder.setCdkey(Apkglobal.getcdkey());
			builder.setUuid(Apkglobal.getuuid());
			builder.setFlow(111);
			builder.setSign("www");
			
			builder.setToken(Apkglobal.gettoken());
			//builder.setUsername("DDDD");//Apkglobal.getuser_name()
			String user = ApkUntils.decodeUnicode(Apkglobal.getuser_name());
			builder.setUsername(user);
			UploadOrderRequest request = builder.build();
			String orderid = request.getOrderid();
			int msgint = syncOne(request);
			if (msgint==0) {
				removeOnePaiedOrder(orderid);	
			}
			
			builder.clear();
		}
	}
	
	private boolean fetchOnePaiedOrder(UploadOrderRequest.Builder builder) {
		OrderTableNew orderTableNew = new OrderTableNew(getApplicationContext());
		String selection = OrderTableNew.CROOM_STATE + "= ?";
		String selectionArgs[] = {"7"};
		
		Cursor cursor = orderTableNew.getCurSor(selection, selectionArgs);
		
		if(cursor == null){
			return false;
		}
		
		String orderid = "";
		if(cursor.moveToNext()) {
			POrderTableNew.Builder tn = POrderTableNew.newBuilder();
			orderid = cursor.getString(cursor.getColumnIndex(OrderTableNew.CORDERID));
			tn.setOrderid(orderid);
			builder.setOrderid(orderid);
			tn.setRoomAliasId(cursor.getString(cursor.getColumnIndex(OrderTableNew.CTABLE_NUM)));
			tn.setRoomMark(cursor.getString(cursor.getColumnIndex(OrderTableNew.CTABLE_EXT)));
			tn.setPeopleCount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CPEOPLE_NUM)));
			tn.setAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CDISH_TOTAL)));
			tn.setRoomState(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CROOM_STATE)));
			tn.setOpenTime(cursor.getString(cursor.getColumnIndex(OrderTableNew.COPEN_TIME)));
			tn.setCloseTime(cursor.getString(cursor.getColumnIndex(OrderTableNew.CCLOSE_TIME)));
			tn.setFinalAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CORDER_PAY)));
			tn.setDiscountRate(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CDIC_RATE)));
			tn.setDiscountAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CDIC_CHARGE)));
			tn.setFreeAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CFREE_CHARGE)));
			tn.setServiceFeeRate(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CSVC_RATE)));
			tn.setServiceAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CSVC_CHARGE)));
			tn.setExtraAmount(cursor.getInt(cursor.getColumnIndex(OrderTableNew.CEXTRA_TOTAL)));
			//tn.setCashuser(cursor.getString(cursor.getColumnIndex(OrderTableNew.CCASHUSER)));
			//tn.setOpenuser(cursor.getString(cursor.getColumnIndex(OrderTableNew.COPENUSER)));
			 utf8str = ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableNew.CCASHUSER)));
			tn.setCashuser(utf8str);
			utf8str = ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableNew.COPENUSER)));
			tn.setOpenuser(utf8str);
//			tn.setCashuser("ddd");
//			tn.setOpenuser("sss");
			
			builder.setOrderTableNew(tn.build());
			cursor.close();
		}
		else {
			cursor.close();
			return false;
		}
		
		if(orderid.length() > 0) {
			
			OrderTableDishs orderTableDishs = new OrderTableDishs(getApplicationContext());
			selection = OrderTableDishs.CORDERID + "= ?";
			selectionArgs[0] = orderid;
			cursor = orderTableDishs.getCurSor(selection, selectionArgs);
			if(cursor != null){
				while(cursor.moveToNext()) {
					POrderTableDishs.Builder tb = POrderTableDishs.newBuilder();
					tb.setOrderid(orderid);
					
					tb.setInnerRankId(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.DISH_ID)));
					tb.setDishId(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.DNBR_VAR)));
					//tb.setDishName("ffffff");
					//tb.setDishName(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DNAM_VAR)));
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DNAM_VAR)));
					tb.setDishName(utf8str);
					tb.setDishCount(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.DISH_NUM)));
					tb.setDishPrice(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.DISH_PRICE)));
//					tb.setDishUnit(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DISH_UNIT)));
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DISH_UNIT)));
					tb.setDishUnit(utf8str);
					
					tb.setUnitInnerRankId(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.UNIT_ID)));
					tb.setIsFree(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.FREE_STATE)));
					tb.setIsCook(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.ORDER_STATE)));
					tb.setOrderMode(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.ORDER_MODE)));
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DCY_NAME)));
					tb.setOrderMan(utf8str);
					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.CZY_NAME))!=null) {
						utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.CZY_NAME)));
						tb.setOperator(utf8str);
					}
					else {
						utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DCY_NAME)));
						tb.setOperator(utf8str);
					}
	
					//tb.setOrderMan(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DCY_NAME)));
//					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.CZY_NAME))==null) {
//						tb.setOperator(cursor.getString(cursor.getColumnIndex(OrderTableDishs.DCY_NAME)));
//					}
//					else {
//						tb.setOperator(cursor.getString(cursor.getColumnIndex(OrderTableDishs.CZY_NAME)));
//					}
				
					tb.setDiscountRate(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.DIC_RATE)));
					tb.setIsServiceCharge(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.SVC_STATE)));
//					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.COOK_CONTENT))!=null) {
//						tb.setCookContent(cursor.getString(cursor.getColumnIndex(OrderTableDishs.COOK_CONTENT)));
//					}
					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.COOK_CONTENT))!=null) {
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableDishs.COOK_CONTENT)));
					tb.setCookContent(utf8str);
					}
//					tb.setCookContent("gggg");
					tb.setCookExtraCharge(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.COOK_EXTRA)));
					tb.setOriginalPrice(cursor.getInt(cursor.getColumnIndex(OrderTableDishs.ORIGINAL_PRICE)));		
					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.LBNAME))==null) {
						tb.setStatClass("1");	
					}
					else {
						tb.setStatClass(cursor.getString(cursor.getColumnIndex(OrderTableDishs.LBNAME)));
					}
					
					
		
					builder.addOrderTableDishs(tb.build());
				}		
				cursor.close();
			}
		}
		
		if(orderid.length() > 0) {
			
			OrderTableSubDishs orderTableSubDishs = new OrderTableSubDishs(getApplicationContext());
			selection = OrderTableDishs.CORDERID + "= ?";
			selectionArgs[0] = orderid;
			cursor = orderTableSubDishs.getCurSor(selection, selectionArgs);
			
			if(cursor != null) {
				while(cursor.moveToNext()) {
					POrderTableSubDishs.Builder tb = POrderTableSubDishs.newBuilder();
					tb.setOrderid(orderid);			
					tb.setInnerRankId(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.DISH_ID)));
					tb.setDishId(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.DNBR_VAR)));
//					tb.setDishName(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.DNAM_VAR)));
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.DNAM_VAR)));
					tb.setDishName(utf8str);
//					tb.setDishName("ffff");
					tb.setDishCount(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.SUBDISH_NUM)));
					tb.setDishPrice(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.SUBDISH_PRICE)));
					tb.setDishUnit(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.SUBDISH_UNIT)));
					tb.setUnitInnerRankId(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.UNIT_ID)));
					tb.setIsCook(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.ORDER_STATE)));
					tb.setOrderMode(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.ORDER_MODE)));
//					tb.setOrderMan(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.DCY_NAME)));
//					tb.setOperator(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.CZY_NAME)));
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.DCY_NAME)));
					tb.setOrderMan(utf8str);
					if (cursor.getString(cursor.getColumnIndex(OrderTableDishs.CZY_NAME))!=null) {
					utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.CZY_NAME)));
					tb.setOperator(utf8str);
					}
					else {
						utf8str=ApkUntils.decodeUnicode(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.DCY_NAME)));
						tb.setOperator(utf8str);	
					}
//					tb.setOrderMan("hhh");
//					tb.setOperator("jjj");
					tb.setDiscountRate(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.DIC_RATE)));
					tb.setIsServiceCharge(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.SVC_STATE)));
					tb.setCookContent(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.COOK_CONTENT)));
					tb.setCookExtraCharge(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.COOK_EXTRA)));
					tb.setOriginalPrice(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.ORIGINAL_PRICE)));		
					tb.setStatClass(cursor.getString(cursor.getColumnIndex(OrderTableSubDishs.LBNAME)));
					tb.setSubInnerRandId(cursor.getInt(cursor.getColumnIndex(OrderTableSubDishs.SUBDISH_ID)));
					
					builder.addOrderTableSubdishs(tb.build());
				}
				cursor.close();				
			}

		}	
		
		if(orderid.length() > 0) {
			
			OrderTablePay orderTablePay = new OrderTablePay(getApplicationContext());
			selection = OrderTablePay.CORDERID + "= ?";
			selectionArgs[0] = orderid;
			cursor = orderTablePay.getCurSor(selection, selectionArgs);
			
			if(cursor != null) {
				while(cursor.moveToNext()) {
					POrderTablePay.Builder tb = POrderTablePay.newBuilder();
					tb.setOrderid(orderid);
					tb.setPaymentName(cursor.getInt(cursor.getColumnIndex(OrderTablePay.PAY_TYPEID)));
					tb.setAmount(cursor.getInt(cursor.getColumnIndex(OrderTablePay.PAY_CHARGE)));
					tb.setExchangeRate(cursor.getInt(cursor.getColumnIndex(OrderTablePay.RATE)));
					tb.setOriginalCashAmount(cursor.getColumnIndex(OrderTablePay.ORIGINAL_AMOUNT));
					
					builder.addOrderTablePay(tb.build());

				}
				cursor.close();				
			}
		}			
	
		return true;
	}
	
	private int syncOne(UploadOrderRequest request) {
		Log.i("OrderSyncService", "start sync...");	  
		//二进制上传，包括可以附带其他参数
		int msgint = -1;
		BinUploader binUploader = new BinUploader();
		binUploader.setUploadUrl(ApkConstant.BaseOrderSyncUrl); //上传的地址
		

		//设置二进制，只能设置一个二进制内容
		binUploader.setBinary(request.toByteArray());
		
		byte[] response = binUploader.upload();
		
		if(response != null) {
			String o = new String(response);
			try {
				JSONObject jsonObj = new JSONObject(o);
				msgint= jsonObj.getInt("ret");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			Log.i(tag, "sync ok, get response length:" + response.length + "resp string:"+o);
		}
		else {
			msgint=-1;
			Log.i(tag, "sync failed");
		}
		
		return msgint;
				
	}
	
	private void removeOnePaiedOrder(String orderid) {
		OrderTableNew orderTableNew = new OrderTableNew(getApplicationContext());
		orderTableNew.deleteByOrderid(orderid);
		
		OrderTableDishs orderTableDishs = new OrderTableDishs(getApplicationContext());
		orderTableDishs.deleteByOrderid(orderid);
		
		OrderTableSubDishs orderTableSubDishs = new OrderTableSubDishs(getApplicationContext());
		orderTableSubDishs.deleteByOrderid(orderid);
		
		OrderTablePay orderTablePay = new OrderTablePay(getApplicationContext());
		orderTablePay.deleteByOrderid(orderid);
	}
	
}
